const express = require('express');
const app = express();
const cors = require('cors')

app.use(cors())

// 接收Post请求的参数
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

const mysql = require('mysql');
const connection = mysql.createConnection({
    host: "localhost",
    port: '3306',
    user: "root",
    password: "123456",
    database: "goods"
});
connection.connect(function (err) {
    if (err) {
        throw err;
    }
    console.log('连接数据库成功了');
});
//增加
app.post('/addData', async (req, res) => {
    let { name, number, price, addtime } = req.body.data;
    let sql = `insert into goodstable(name,number,price,addtime)value('${name}','${number}','${price}','${addtime}')`;
    connection.query(sql,function(err,result){
        if (result.affectedRows) {
            res.json({ code: 200, message: '成功' })
        } else {
            res.json({ code: -1, message: '失败' })
        }
    })
  
})
//删除
app.post('/delete',async(req,res)=>{
    let {id} = req.body;
    let sql = `delete from goodstable where id = ${id}`;
    connection.query(sql,function(err,result){
        if (result.affectedRows) {
            res.json({ code: 200, message: '成功' })
        } else {
            res.json({ code: -1, message: '失败' })
        }
    })
})

// 更新
app.post('/edit',async(req,res)=>{
    let {id} = req.body;
    let sql = `select * from goodstable where id = ${id}`;
    connection.query(sql,function(err,result){
        res.json(result)
    })
})
app.post('/update',async(req,res)=>{
    let {id, name, number, price, addtime} =req.body.data;
    let sql = `update goodstable set name = "${name}",number="${number}",price="${price}",addtime="${addtime}" where id = "${id}"`;
    connection.query(sql,function(err,result){
        if (result.affectedRows) {
            res.json({ code: 200, message: '成功' })
        } else {
            res.json({ code: -1, message: '失败' })
        }
    })
})
//查询
app.get('/index', (req, res) => {
    let sql = `select * from goodstable`;
    connection.query(sql, function (err, data) {
        res.json(data)
    })
})

app.listen(4000, () => {
    console.log('端口号4000,服务器启动');
})